package com.huage.courseplatform.application.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huage.courseplatform.application.mapper.FileMapper;
import com.huage.courseplatform.application.model.entity.SysFile;
import com.huage.courseplatform.application.service.FileService;


import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import org.springframework.util.Assert;
import org.springframework.util.FileSystemUtils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, SysFile> implements FileService {
    @Override
    public SysFile uploadFile(MultipartFile multipartFile,String type) throws IOException {

        SysFile sysFile = new SysFile();

        //目录路径
        String realPath = System.getProperty("user.dir")+"/upload";
        if(type.equals("image")){
            realPath+= "/img/";
            sysFile.setType("image");
            sysFile.setPath("/upload/img");
        }
        if(type.equals("video")){
            realPath+= "/video/";
            sysFile.setType("video");
            sysFile.setPath("/upload/video");
        }
        //上传原文件名
        String uploadName = multipartFile.getOriginalFilename();
        //后缀名获取
        String exts = "."+uploadName.substring(uploadName.lastIndexOf(".") + 1);

        String uuidName = UUID.randomUUID().toString().trim().replaceAll("-", "");
        //新文件名
        String fileName  = uuidName.concat(exts);
        //保存文件
        File file = new File(realPath + fileName);

        // 如果不存在则创建目录
        if(!file.exists()){
            file.mkdirs();
        }
        multipartFile.transferTo(file);

        sysFile.setFileName(uuidName);
        sysFile.setExt(uploadName.substring(uploadName.lastIndexOf(".") + 1));
        String realName = multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().lastIndexOf("."));
        sysFile.setRealName(realName);
        sysFile.setSize(multipartFile.getSize());
        baseMapper.insert(sysFile);

        return sysFile;
    }

    @Override
    public String deleteFile(String fileId) {
        SysFile sysFile = baseMapper.selectById(fileId);
        Assert.isTrue(ObjectUtils.isNotEmpty(sysFile),"删除失败，查找不到文件");
        String realPath = System.getProperty("user.dir");
        String filePath = realPath + sysFile.getPath()+"/"+sysFile.getFileName()+"."+sysFile.getExt();

        FileSystemUtils.deleteRecursively(new File(filePath));
        baseMapper.deleteById(fileId);
        return fileId;
    }
}
